<?php
namespace app\api\controller;

use app\common\model\Coupon;
use app\common\model\Shoporder;
use app\common\model\FightTeam;
use app\common\model\User;
use app\common\model\Money as moneyModel;
use app\common\model\Goods;
use app\common\model\UserCoupon;
use think\Controller;
use think\facade\Cache;
use think\Db;

use think\Request;
use Endroid\QrCode\QrCode;

class Pay extends Controller
{
	public function pay(){
		$data = [
			'code' => 1, 'msg' => '数据异常',
		];
		if(request()->isPost()) {
			require_once "wxpay/lib/WxPay.Api.php";
			require_once "wxpay/example/WxPay.Config.php";
			require_once "wxpay/example/WxPay.JsApiPay.php";
			$tools = new \JsApiPay();
			$openId = session('openid');
			$userid = session('userid');
			$coupon_id = $this->request->param('coupon_id')?$this->request->param('coupon_id'):0;
			$fight_id= $this->request->param('fight_id')?$this->request->param('fight_id'):0;
			$goods_id = $this->request->param('goods_id');
			$coupon_id = 3;
			$goods_id = 44;
			$goods_info = Goods::where('id',$goods_id)->find();
			if(empty($goods_info)){
				$data = [
					'code' => 1, 'msg' => '商品不存在',
				];
				return json($data);
			}
			if($goods_info['cat_id'] == 12 && $goods_info['end_time'] <time()){
				$data = [
					'code' => 1, 'msg' => '商品活动已结束',
				];
				return json($data);
			}
			if($goods_info['amount'] <=0 ||   $goods_info['is_on'] == '否' ){
				$data = [
					'code' => 1, 'msg' => '商品已售罄',
				];
				return json($data);
			}
			switch($goods_info['cat_id']){
				//如果是拼团商品
				case 11:
				$type= $this->request->param('type')?$this->request->param('type'):0;//0是发起拼单 1是参与拼单 2是单独购买
				if($type == 0){
					$data1 = [
						'goods_id' => $goods_id,
						'userid' => $userid,
						'status' => 0,
						'expired_time' => time() + $goods_info['fight_time'],
					];
					$fight_id = FightTeam::insertGetId($data1);
					if ($fight_id) {
						$price = (float)$goods_info['fighting_price'];
					}
				}elseif($type == 1){
					//如果是参与拼单
					$info = FightTeam::where(['id' => $fight_id, 'status' => 0, 'goods_id' => $goods_id])->find();
					//看已经加入该拼团的人数
					if ($info && $info['status'] == 0) {
						$fight_count = Shoporder::where('fight_id', $fight_id)->where('status','in','0,1')->count();
						if ($fight_count == $goods_info['people_count']) {
							//如果该团已经满了 ，就改变状态
							FightTeam::where('id', $fight_id)->update(['status' => 1]);
						}
						if ($fight_count >= $goods_info['people_count']) {
							$data = [
								'code' => 1, 'msg' => '该拼团已满',
							];
							return json($data);
						}
						if($info['userid'] == $userid){
							$data = [
								'code' => 1, 'msg' => '不能参加自己的拼团哦',
							];
							return json($data);
						}
					} else {
						$data = [
							'code' => 1, 'msg' => '该拼团不存在',
						];
						return json($data);
					}
					$price = (float)$goods_info['fighting_price'];
				}elseif($type == 2){
					$price = (float)$goods_info['sale_price'];
				}
				break;
				//如果是秒杀商品
				case 12:
					$price = (float)$goods_info['price_spike'];
					break;
				default :
					$price = (float)$goods_info['sale_price'];
			}
			//判断优惠券是否可以用
			$coupon_info = UserCoupon::alias('u')->join('langjin_coupon c','c.id = u.coupon_id')->where('u.id',$coupon_id)->where('u.userid',$userid)->where('c.expired_time','<',time())->field('u.coupon_id,u.status,c.full_amount,c.amount')->find();
				if ($coupon_info && $coupon_id) {
					if($coupon_info['status'] != 0){
						$data = [
							'code' => 1, 'msg' => '优惠券已使用',
						];
						return json($data);
					}
					$coupon_cat = Coupon::where('id',$coupon_info['coupon_id'])->find();
					if($coupon_cat['cat_id'] == 2){
						//如果是满减优惠券的话看能不能用
						if(bccomp($price, $coupon_cat['full_amount'], 2) <0){
							$data = [
								'code' => 1, 'msg' => '优惠券不可用',
							];
							return json($data);
						}
						$price = $price-$coupon_cat['amount'];
					}else{
						if(bccomp($price, $coupon_cat['amount'], 2) <0){
							$data = [
								'code' => 1, 'msg' => '优惠券不可用',
							];
							return json($data);
						}
						$price = $price-$coupon_cat['amount'];
					}
				}else{
					$coupon_id = 0;
				}
			$order_number = $this->make_order($goods_id, $price,$coupon_id,$fight_id);
			if (!$order_number) {
				$data = [
					'code' => 1, 'msg' => '数据异常',
				];
				return json($data);
			}
			//②、统一下单
			$input = new \WxPayUnifiedOrder();
			$input->SetBody("pay");
			$input->SetAttach("test");
			$input->SetOut_trade_no($order_number);//订单号
			$input->SetTotal_fee(1);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			$input->SetGoods_tag("test");
			$input->SetNotify_url($_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . "/api/login/response");
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid($openId);
			$config = new \WxPayConfig();
			$order = \WxPayApi::unifiedOrder($config, $input);
			//echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
			//printf_info($order);
			$jsApiParameters = $tools->GetJsApiParameters($order);
			$data = [
				'code' => 0, 'msg' => '获取成功', 'info' => $jsApiParameters
			];
			return json($data);
		}
		return json($data);
		//print_r($jsApiParameters);exit;
		//$this->assign('jsApiParameters', $jsApiParameters);
		//return $this->fetch();
	}
	//创建订单
	public function make_order($goods_id,$price,$coupon_id,$fight_id){
		$data['order_number'] = $this->createordernum();
		$data['userid'] = session('userid');
		$data['goods_id'] = $goods_id;
		$data['num'] = 1;
		$data['poundage'] = 0;
		$data['tprice'] = $price;
		$data['status'] = 0;
		$data['coupon_id'] = $coupon_id;
		$data['fight_id'] = $fight_id;
		$res = Shoporder::create($data);
		if($res){
			Goods::where('id',$goods_id)->setDec('amount',1);
			return $data['order_number'];
		}else{
			return false;
		}
	}
	//生成唯一订单号
	public function createordernum()
	{
		$order_number=mt_rand(100000,999999).substr(microtime(), 2, 5).date('YmdHis');
		//判断是否已存在
		$result=Shoporder::where('order_number',$order_number)->find();
		if(!$result){
			return $order_number;
		}else{

			return $this->createordernum();
		}

	}
	//获得商品价格
	public function get_price($goods_id){
		$info = Goods::where('id',$goods_id)->field('cat_id,sale_price,fighting_price,price_spike')->find();
		switch($info['cat_id']){
			//如果是拼团商品
			case 11:
				return $info['fighting_price'];
			//如果是秒杀商品
			case 12:
				return $info['price_spike'];
			default:
				return $info['sale_price'];
		}
	}
}